package top.rainbowecho.notify.infrastructure.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import top.rainbowecho.common.mq.mo.MailMeta;
import top.rainbowecho.notify.domain.model.email.QqEmail;
import top.rainbowecho.notify.domain.model.email.decorator.TemplateMail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

/**
 * @author rainbow
 * @since 2019/12/13 15:46
 */
@Component
@Slf4j
@PropertySource("classpath:application.yml")
public class MailMqListener {
    private QqEmail postman;

    @Autowired
    public void setPostman(QqEmail postman) {
        this.postman = postman;
    }

    @RabbitListener(queues = "${blog.mq.routes.gatewayToMail.routing}")
    public void listenFromGateway(MailMeta mailMeta, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException, MessagingException {
        log.debug("接收到的mail meta数据为：" + mailMeta);
        TemplateMail templateMail = new TemplateMail(postman);
        MimeMessage mess = templateMail.generateHtmlMail(mailMeta);

        channel.basicAck(deliveryTag, false);
        templateMail.send(mess);
    }
}
